package controller

import (
	"github.com/gin-gonic/gin"
	"go-web/model"
	"go-web/service"
	"go-web/util"
	"log"
	"net/http"
	"strconv"
)

type UserController struct {
	userService *service.UserService
}

func NewUserController() *UserController {
	return &UserController{userService: service.NewUserService()}
}

func (c *UserController) RegisterRoutes(router *gin.RouterGroup) {
	userRouter := router.Group("/user")
	{
		userRouter.POST("", c.CreateUser)
		userRouter.GET("", c.ListUsers)
		userRouter.GET("/:id", c.GetUser)
		userRouter.PUT("/:id", c.UpdateUser)
		userRouter.DELETE("/:id", c.DeleteUser)
	}
}

func (c *UserController) CreateUser(ctx *gin.Context) {
	var user model.User
	if err := ctx.ShouldBindJSON(&user); err != nil {
		util.ErrorResponse(ctx, http.StatusBadRequest, "Invalid request payload")
		return
	}

	if err := c.userService.CreateUser(&user); err != nil {
		util.ErrorResponse(ctx, http.StatusInternalServerError, "Failed to create user")
		return
	}

	util.SuccessResponse(ctx, http.StatusCreated, user)
}

func (c *UserController) GetUser(ctx *gin.Context) {
	id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
	if err != nil {
		util.ErrorResponse(ctx, http.StatusBadRequest, "Invalid user ID")
		return
	}

	user, err := c.userService.GetUserByID(uint(id))
	if err != nil {
		util.ErrorResponse(ctx, http.StatusNotFound, "User not found")
		return
	}

	util.SuccessResponse(ctx, http.StatusOK, user)
}

func (c *UserController) ListUsers(ctx *gin.Context) {
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("page_size", "10"))

	users, total, err := c.userService.ListUsers(page, pageSize)
	if err != nil {
		log.Printf("ListUsers ERROR: %v", err) // 关键：打印完整错误链
		util.ErrorResponse(ctx, http.StatusInternalServerError, "Failed to list users")
		return
	}

	response := gin.H{
		"data":  users,
		"total": total,
		"page":  page,
	}

	util.SuccessResponse(ctx, http.StatusOK, response)
}

func (c *UserController) UpdateUser(ctx *gin.Context) {
	id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
	if err != nil {
		util.ErrorResponse(ctx, http.StatusBadRequest, "Invalid user ID")
		return
	}

	var user model.User
	if err := ctx.ShouldBindJSON(&user); err != nil {
		util.ErrorResponse(ctx, http.StatusBadRequest, "Invalid request payload")
		return
	}

	user.ID = uint(id)
	if err := c.userService.UpdateUser(&user); err != nil {
		util.ErrorResponse(ctx, http.StatusInternalServerError, "Failed to update user")
		return
	}

	util.SuccessResponse(ctx, http.StatusOK, user)
}

func (c *UserController) DeleteUser(ctx *gin.Context) {
	id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
	if err != nil {
		util.ErrorResponse(ctx, http.StatusBadRequest, "Invalid user ID")
		return
	}

	if err := c.userService.DeleteUser(uint(id)); err != nil {
		util.ErrorResponse(ctx, http.StatusInternalServerError, "Failed to delete user")
		return
	}

	util.SuccessResponse(ctx, http.StatusNoContent, nil)
}
